package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *在执行目标方法之前，执行该过滤方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

		//从请求头对象中获取token
        String token = request.getHeader("token");
        if(token==null){
            //否则，发送未认证错误信息
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //2.校验token是否有效
        Claims claimsBody = JwtUtil.getClaimsBody(token);
        // -1：有效，0：有效，1：过期，2：过期
        int i = JwtUtil.verifyToken(claimsBody);
        if(i==-1 || i==0){//有效
            //把用户id封装到ThreadLocal对象中
            Integer id = (Integer) claimsBody.get("id");
            BaseContext.setCurrentId(id.longValue());

            //如果有登录数据，代表一登录，放行
            return true;
        } else{
			//否则，发送未认证错误信息
			response.setStatus(401);
            return false;
        }
    }
}
